﻿
#Const use_thread_static = True
Imports osi.root.connector
Imports osi.root.template
Imports osi.root.formation

Public Class call_stack(Of T)
    Inherits call_stack(Of T, _max_uint8)
End Class

Public Class call_stack(Of T, MAX_SIZE As _int64)
    'the implementation of threadstatic valuetype object is not consistent between mono and .net
    'while .net has boxing by default
#If use_thread_static Then
    Private Shared ReadOnly c As thread_static(Of wrapper(Of fixed_stack(Of T, MAX_SIZE)))

    Shared Sub New()
        c = New thread_static(Of wrapper(Of fixed_stack(Of T, MAX_SIZE)))()
    End Sub
#Else
    <ThreadStatic()> Private Shared c As wrapper(Of fixed_stack(Of T, MAX_SIZE))
#End If

    Public Shared Property current() As T
        Get
#If use_thread_static Then
#If DEBUG Then
            assert(Not (+c) Is Nothing)
#End If
            Return (+c).back()
#Else
#If DEBUG Then
            assert(Not c Is Nothing)
#End If
            Return c.back()
#End If
        End Get
        Set(ByVal value As T)
            Dim s As wrapper(Of fixed_stack(Of T, MAX_SIZE)) = Nothing
#If use_thread_static Then
            s = (+c)
#Else
            s = c
#End If
            If s Is Nothing Then
                s = New wrapper(Of fixed_stack(Of T, MAX_SIZE))()
#If use_thread_static Then
                c.set(s)
#Else
                c = s
#End If
            End If
            If value Is Nothing Then
                s.pop()
            Else
                s.emplace_push(value)
            End If
        End Set
    End Property
End Class
